package com.woniuxy.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.woniuxy.entity.PageBean;
import com.woniuxy.entity.Relationship;
import com.woniuxy.realm.CustomizedToken;
import com.woniuxy.realm.LoginType;
import com.woniuxy.utils.CodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.woniuxy.dao.DynamicDao;
import com.woniuxy.entity.Coach;
import com.woniuxy.entity.Dynamic;
import com.woniuxy.entity.MyStudent;
import com.woniuxy.entity.PageBean;
import com.woniuxy.entity.Message;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.entity.Signing;
import com.woniuxy.entity.User;
import com.woniuxy.entity.Venue;
import com.woniuxy.exception.CustomExceptionResolver;
import com.woniuxy.service.CoachService;
import com.woniuxy.service.DynamicService;
import com.woniuxy.service.OrderService;
import com.woniuxy.service.SigningService;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.CodeUtils;
import com.woniuxy.service.MessageService;
import com.woniuxy.service.UserService;
import com.woniuxy.service.VenueService;
import com.woniuxy.utils.PhoneCode;
import com.woniuxy.utils.RegexUtils;
import com.woniuxy.utils.TimeUtils;

import lombok.Data;

@RestController
@RequestMapping("/coach")
public class CoachController {

	@Autowired
	private CoachService coachService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private DynamicService dynamicService;
	@Autowired
	private UserService userService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private VenueService venueService;
	@Autowired
	private SigningService signingService;

	private static final String COACH_LOGIN_TYPE= LoginType.COACH.toString();

	/**
	 * 查找所有的教练
	 * 
	 * @return ResponseEntity
	 */
	@RequestMapping("/findCoach")
	@ResponseBody
	public ResponseEntity<List<Coach>> findCoach() {
		ResponseEntity<List<Coach>> coachListResponseEntity = new ResponseEntity<>();
		List<Coach> coaches = coachService.findCoach();
		if (coaches != null && coaches.size() != 0) {
			return coachListResponseEntity.setMsg("所有教练").setCode(CodeUtils.SUCCESS_CODE).setData(coaches);
		}
		return coachListResponseEntity.setMsg("啥都没有").setCode(CodeUtils.ERROR_CODE);
	}

	/*
	 * 教练注册
	 */
	@RequestMapping("/regist")
	@ResponseBody
	public ResponseEntity<Void> addCoach(Coach coach, String code, HttpServletRequest request) {
		RegexUtils reg = new RegexUtils();
		if (!reg.accountIsRight(coach.getCname())) {
			return ResponseEntity.ERROR.setMsg("账号必须是以字母，数字，英文，中文，下划线组成，长度2~10");
		}
		if (!reg.passwordIsRight(coach.getPwd())) {
			return ResponseEntity.ERROR.setMsg("密码长度必须为6到12");
		}
		if (!reg.telphoneIsRight(coach.getPhoneNumber())) {
			return ResponseEntity.ERROR.setMsg("手机号错误");
		}
		if (code == null || code.trim() == "") {
			return ResponseEntity.ERROR.setMsg("验证码不能为空");
		}
		HttpSession session = request.getSession();
		String recode = (String) session.getAttribute("recode");
		if (!recode.equals(code)) {
			return ResponseEntity.ERROR.setMsg("验证码错误");
		}
//		String pwd = new SimpleHash("MD5", coach.getPwd(), coach.getCname(), 1024).toString();
//		coach.setPwd(pwd);
		int num = coachService.addCoach(coach);
		System.out.println(num);
		if (num == 1) {
			return ResponseEntity.SUCCESS;
		}
		if (num == 2) {
			return ResponseEntity.ERROR.setMsg("该账号已存在");
		}
		if (num == 3) {
			return ResponseEntity.ERROR.setMsg("该手机号已存在");
		}
		return ResponseEntity.ERROR.setMsg("系统维护中");
	}

	/*
	 * 发送验证码
	 */
	@RequestMapping("/sendCode")
	@ResponseBody
	public ResponseEntity<Void> sendCode(String phoneNumber, HttpServletRequest request) {
		// 判断传入的手机号是否正确
		System.out.println(phoneNumber);
		if (!RegexUtils.telphoneIsRight(phoneNumber)) {
			// 如果手机号不正确则返回305 为手机号错误
			return ResponseEntity.ERROR.setMsg("手机号错误!");
		}
		Coach isCoach = coachService.findCoachByPhoneNumber(phoneNumber);
		if (isCoach != null) {
			return ResponseEntity.ERROR.setMsg("该手机号已存在");
		}
		PhoneCode phoneCode = new PhoneCode();
		// 获取随机验证码
		String code = phoneCode.getCode();
		// 接收短信的手机号
		String phone = phoneNumber;
		// 调用发短信的方法
		phoneCode.sendCode(phone, code);
		HttpSession session = request.getSession();
		session.setAttribute("recode", code);
		/* System.out.println(session.getAttribute("code")); */
		return ResponseEntity.SUCCESS;
	}

	/*
	 * 通过账号登录
	 */
	@RequestMapping("/logincname")
	@ResponseBody
	public ResponseEntity<Void> logincname(Coach coach, HttpSession httpSession, HttpServletRequest request,@RequestParam(value = "rm", defaultValue = "false") boolean rm) {
		// 1.获取主题对象，subject 当前用户 对应一个客户端程序
		Subject currentUser = SecurityUtils.getSubject();
		// 获取shiro的session
		Session session = currentUser.getSession();
		System.out.println(coach.getPwd());
		if (!RegexUtils.passwordIsRight(coach.getPwd())) {
			// 判断用户名是否正确不正确返回306代表账号错误
			return ResponseEntity.ERROR.setCode(307).setMsg("密码错误应输入6-12位数字密码");
		}
		if (!currentUser.isAuthenticated()) {
			// 没认证过
			// 将账号密码信息封装成token，方便后面认证的操作
			String pwd = new SimpleHash("MD5", coach.getPwd(), coach.getCname(), 1024).toString();
			CustomizedToken customizedToken = new CustomizedToken(coach.getCname(), pwd, COACH_LOGIN_TYPE);
			// 判断用户是否勾选
			if (rm) {
				// 开启记住我的功能
				customizedToken.setRememberMe(true);
			}
			// 当前“用户”拿着令牌去安全管理器中进行身份的认证，会将令牌交给securitymanager进行认证
			try {
				currentUser.login(customizedToken);
				Coach coach1 = coachService.findCoachByCname(coach.getCname());
				httpSession.setAttribute("coach", coach1);
				System.out.println("认证成功");
				return ResponseEntity.SUCCESS;
				// 不报任何异常，表示账号不存在
			} catch (UnknownAccountException e) {
				// 账号不存在 info为空
				System.out.println("账号不存在");
				return ResponseEntity.ERROR.setCode(4);
			} catch (IncorrectCredentialsException e) {
				// 密码错误
				return ResponseEntity.ERROR.setCode(3);
			} catch (AuthenticationException e) {
				// 其他异常
				return ResponseEntity.ERROR.setCode(500);
			}
		}
		return ResponseEntity.ERROR;

	}

	/**
	 * 根据id查教练
	 * 
	 * @param cid 教练id
	 * @return ResponseEntity
	 */
	@GetMapping("/coachById/{cid}")
	@ResponseBody
	public ResponseEntity<Coach> findCoachById(@PathVariable("cid") int cid) {
		ResponseEntity<Coach> coachResponseEntity = new ResponseEntity<>();
		Coach coachById = coachService.findCoachById(cid);
		if (coachById != null) {
			return coachResponseEntity.setData(coachById).setMsg("这是一个教练").setCode(CodeUtils.SUCCESS_CODE);
		}
		return coachResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("查无此人");
	}

	/**
	 * 按条件分页查询
	 * 
	 * @param coach 查询条件
	 * @return ResponseEntity<PageBean<Coach>>
	 */
	@RequestMapping(value = "/condition/{page}/{pageSize}", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<PageBean<Coach>> findCoachByCondition(@RequestBody Coach coach,
			@PathVariable("page") int page, @PathVariable("pageSize") int pageSize) {
		ResponseEntity<PageBean<Coach>> responseEntity = new ResponseEntity<>();
		// is null?
		if (coach == null) {
			return responseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("查询异常");
		}
		PageBean<Coach> coachPageBean = coachService.findCoachByCondition(coach, page, pageSize);
		// 将pageBean放入响应体中返回前端
		return responseEntity.setData(coachPageBean).setMsg("这是你要的教练们").setCode(CodeUtils.SUCCESS_CODE);
	}

	/*
	 * 通过手机号登录
	 */
	@RequestMapping("/loginphone")
	@ResponseBody
	public ResponseEntity<Void> loginPhone(Coach coach, HttpSession session, HttpServletRequest request) {
		RegexUtils reg = new RegexUtils();
		if (!reg.telphoneIsRight(coach.getPhoneNumber())) {
			return ResponseEntity.ERROR.setMsg("手机号错误");
		}
		if (!reg.passwordIsRight(coach.getPwd())) {
			return ResponseEntity.ERROR.setMsg("密码长度必须为6到12");
		}
		Coach coach1 = coachService.findCoachByPhoneNumber(coach.getPhoneNumber());
		if (coach1 == null) {
			return ResponseEntity.ERROR.setMsg("账号或密码错误");
		}
		if (!coach1.getPwd().equals(coach.getPwd())) {
			return ResponseEntity.ERROR.setMsg("账号或密码错误");
		}
		HttpSession session1 = request.getSession();
		session1.setAttribute("coach", coach1);
		session.setAttribute("cid", coach1.getCid());
		return ResponseEntity.SUCCESS;

	}

	/*
	 * 1.教练个人信息完善
	 * 
	 */
	@RequestMapping("/updateCoachInformation")
	@ResponseBody
	public ResponseEntity<Void> updateCoachInformation(Coach coach, HttpSession session) {
		int cid = (int) session.getAttribute("cid");
		// 风格数据校验
		String regex1 = "^[01234]{1}$";
		String styleId = Integer.toString(coach.getStyleId());
		if (!styleId.matches(regex1)) {
			return ResponseEntity.ERROR.setMsg("风格选择错误");
		}
		// 信息是否公开
		String regex2 = "^[01]{1}$";
		if (coach.getIsOpen() != null && coach.getIsOpen().trim().equals("") && !coach.getIsOpen().matches(regex2)) {
			return ResponseEntity.ERROR.setMsg("信息是否公开选择错误");
		}
		// 是否接课
		String regex3 = "^[01]{1}$";
		if (coach.getIsAccept() != null && coach.getIsAccept().trim().equals("")
				&& !coach.getIsAccept().matches(regex3)) {
			return ResponseEntity.ERROR.setMsg("是否接课选择错误");
		}
		// 是否签约
		if (coach.getIsBand() != null && coach.getIsBand().trim().equals("") && !coach.getIsBand().matches(regex3)) {
			return ResponseEntity.ERROR.setMsg("是否签约选择错误");
		}
		// 是否满课
		if (coach.getIsFull() != null && coach.getIsFull().trim().equals("") && !coach.getIsFull().matches(regex3)) {
			return ResponseEntity.ERROR.setMsg("是否满课选择错误");
		}
		// 是否私教
		if (coach.getIsPrivate() != null && coach.getIsPrivate().trim().equals("")
				&& !coach.getIsPrivate().matches(regex3)) {
			return ResponseEntity.ERROR.setMsg("是否私教选择错误");
		}
		// 课时费(0-1000)
		BigDecimal min = new BigDecimal(0);
		BigDecimal max = new BigDecimal(1000);
		if (coach.getPrice() != null
				&& !(coach.getPrice().compareTo(min) != -1 && coach.getPrice().compareTo(max) != 1)) {
			return ResponseEntity.ERROR.setMsg("课时费为0-1000");
		}
		// 昵称
		RegexUtils reg = new RegexUtils();
		if (coach.getNickname() != null && !coach.getNickname().trim().equals("")
				&& !reg.nicknameIsRight(coach.getNickname())) {
			return ResponseEntity.ERROR.setMsg("昵称必须是以字母，数字，英文，中文，下划线组成，长度1~10");
		}
		int code = coachService.updateCoachInformation(coach, cid);
		if (code == 1) {
			return ResponseEntity.SUCCESS;
		} else {
			return ResponseEntity.ERROR.setCode(code);
		}

	}

	/*
	 * 2.教练个人地址完善
	 */
	@RequestMapping("/updateAddressByCid")
	@ResponseBody
	public ResponseEntity<Void> updateAddressByCid(String address, BigDecimal longitude, BigDecimal latitude,
			HttpSession session) {
		int cid = (int) session.getAttribute("cid");
		// 修改地址信息
		int code = coachService.updateAddressByCid(address, cid, longitude, latitude);
		if (code == 1) {
			// 修改成功
			return ResponseEntity.SUCCESS;
		} else {
			return ResponseEntity.ERROR.setCode(code);
		}
	}

	/*
	 * 3.教练头像修改
	 */
	@RequestMapping("/updateAvatarByCid")
    @ResponseBody
    public ResponseEntity updateAvatarByUid(MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println(file.getOriginalFilename()+"-------------------------------");
        //获取图片名字
        String filename=file.getOriginalFilename();
        int index = filename.lastIndexOf(".");
        String type = filename.substring(index);
        //给图片命名
        String filenames = UUID.randomUUID().toString() + type;
        // 得到存放文件的目录
        String path = request.getServletContext().getRealPath("");// 当前项目的根路径
        File root = new File(path);
        File main= root.getParentFile();
        File fileDir = new File(main, "resources/static/images");
        /*System.out.println(fileDir+"++++++++++++++++++++++++++++++++++++++++");*/
        if (!fileDir.exists()) {
            fileDir.mkdirs(); // 创建
        }
        // 得到文件存储的路径 files/文件名
        filename = fileDir.getAbsolutePath() + File.separator + filenames;
       /* System.out.println(filename+"**************************************");*/
        File destFile = new File(filename);
        try {
            file.transferTo(destFile);// 写入磁盘
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        HttpSession session=request.getSession();
    	Coach coach = (Coach) session.getAttribute("coach");
        /*int uid=user.getUid();*/
        int cid=coach.getCid();
        //修改信息
        String avatar="../../images/"+filenames;
        int error=coachService.updateAvatarByCid(avatar,cid);
        if (error==1){
            //修改成功
            return  ResponseEntity.SUCCESS;
        }else {
            return ResponseEntity.ERROR.setCode(error);
        }
    }
	
	/*
	 * 查询已登录教练个人信息
	 */
	@RequestMapping("/findCoachByCid")
	@ResponseBody
	public ResponseEntity<Coach> findCoachByCid(HttpSession session) {
		int cid = (int) session.getAttribute("cid");
		Coach coach = coachService.findCoachByCid(cid);
		ResponseEntity entity = new ResponseEntity<Coach>(coach);
		return entity;
	}

	// 对教练空闲时间进行修改
	@RequestMapping("/coachfreetime")
	@ResponseBody
	public ResponseEntity reSetFreeTime(int day, int when, HttpServletRequest request) {
		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		//
		return null;
	}
	// 钱包

	@RequestMapping("/wallet")
	@ResponseBody
	public ResponseEntity<Coach> myWallet(HttpServletRequest request) {
		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// System.out.println(cid);
		// 将当前账户信息返回页面
		// int cid = 100001;
		ResponseEntity<Coach> responseEntity = new ResponseEntity<>();
		// return responseEntity.setData(coachService.findCoachByCid(cid));

		return responseEntity.setData(coachService.findCoachByCid(coach.getCid()));

	}

	// 绑定银行卡

	@RequestMapping("/bankcard")
	@ResponseBody
	public ResponseEntity<Void> myCard(String bankCard, HttpServletRequest request) {

		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// System.out.println(coach);
		// System.out.println(RegexUtils.cardIsRight(coach.getBankCard()));
		// Coach coach = new Coach();
		// coach = coachService.findCoachByCid(100003);
		coach.setBankCard(bankCard);
		// 判断银行卡号合法性
		if (RegexUtils.cardIsRight(coach.getBankCard())) {

			return ResponseEntity.ERROR.setMsg("银行卡不合法！");

		} else {

			if (coachService.insertBankCard(coach) == 1) {

				return ResponseEntity.SUCCESS.setMsg("添加成功！");

			} else {

				return ResponseEntity.ERROR.setMsg("卡号已存在，请勿重复添加！");

			}

		}

	}

	// 取现

	@RequestMapping("/cash")
	@ResponseBody
	public ResponseEntity<Void> cashing(BigDecimal money, HttpServletRequest request) {

		// System.out.println(myWallet(cid).getData().getMoney());
		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// Coach coach = new Coach();
		// coach = coachService.findCoachByCid(100001);
		coach.setMoney(money);
		int num = coachService.updateMoney(coach);

		if (num == 2) {

			return ResponseEntity.ERROR.setMsg("余额不足！");

		} else if (num == 1) {

			return ResponseEntity.SUCCESS.setMsg("取款成功");

		} else {

			return ResponseEntity.ERROR.setMsg("取款失败！");

		}

	}

	// 密码找回

	// 发送验证码

	@RequestMapping("/sendcode")
	@ResponseBody
	public ResponseEntity<Void> sendCardCode(String phoneNumber, HttpServletRequest request) {

		PhoneCode phoneCode = new PhoneCode();

		// 获取随机的验证码 String
		String code = phoneCode.getCode();

		// 接受验证码的手机
		String phone = phoneNumber;

		// 调用发短信的方法
		phoneCode.sendCode(phone, code);
		HttpSession session = request.getSession();
		session.setAttribute("code", code);
		return ResponseEntity.SUCCESS.setMsg("验证码已发送！");

	}

	// 比较验证码，修改密码

	@RequestMapping("/resetpwd")
	@ResponseBody
	public ResponseEntity<Void> resetPwd(String newpwd, HttpServletRequest request, String accptcode) {

		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");

		String code = (String) session.getAttribute("code");

		if (code.equals(accptcode)) {

			// int num = coachService.updatePwd(100003, newpwd);
			int num = coachService.updatePwd(coach.getCid(), newpwd);

			if (num == 1) {

				return ResponseEntity.SUCCESS.setMsg("密码修改成功！");

			}

		}

		return ResponseEntity.ERROR.setMsg("验证码错误！");

	}

	// 教练关注
	// 分页查询教练的关注

	// 教练的所有关注列表,分页查询
	@RequestMapping("/coachrelationship")
	@ResponseBody
	public ResponseEntity<PageBean<Relationship>> selectRelationship(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		//System.out.println(coach.getCid());
		// User user=(User)session.getAttribute("user");
		ResponseEntity<PageBean<Relationship>> entity = new ResponseEntity<PageBean<Relationship>>();
		// 通过账号获取cid
		// int cid = 100001;
		 //PageBean<Relationship> relationship = coachService.getByPage(page, cid);
		PageBean<Relationship> relationship = coachService.getByPage(page, coach.getCid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(relationship);
		return entity;
	}

	// 教练添加关注

	// 输入账号查询结果，返回页面
	@RequestMapping("/findrelationship")
	@ResponseBody

	public ResponseEntity findRelationship(int id, HttpServletRequest request) {
		// 获取当前用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// Coach coach = coachService.findCoachByCid(100001);
		
		// 去学员表查找学员数据
		if (id > 10000000) {
			User user = new User();
			// System.out.println(id);
			// 根据被关注者id去查找被关注者信息
			user = userService.findUserByUid(id);
			ResponseEntity<User> entity = new ResponseEntity<>();
			entity.setData(user);
			// return ResponseEntity.SUCCESS.setMsg("添加成功！").setData(user);
			return entity;
			// 去教练表查找教练信息
		} else if (100000 < id && id < 10000000) {
			Coach coach2 = coachService.findCoachByCid(id);
			ResponseEntity<Coach> entity = new ResponseEntity<>();
			entity.setData(coach2);
			return entity;
			// return ResponseEntity.SUCCESS.setMsg("添加成功！");
			// 去场馆表查找场馆
		} else if (id < 100000) {
			Venue venue = new Venue();
			venue = venueService.findVenueByVenueId(id);
			ResponseEntity<Venue> entity = new ResponseEntity<>();
			entity.setData(venue);
			return entity;
			// return ResponseEntity.SUCCESS.setMsg("添加成功！");
		}

		return ResponseEntity.ERROR.setMsg("未找到结果！");
	}
	
	//根据姓名模糊查询账户信息，返回页面
	@RequestMapping("findrelationship2")
	@ResponseBody
	public ResponseEntity findDataByName(String name){
		
		/*System.out.println(name);
		System.out.println(id);
		Coach coach=new Coach();
		Venue venue=new Venue();
		User user=new User();
		if (name==null&&id!=null) {
			coach.setCid(id);
			venue.setVid(id);
			user.setUid(id);
		}else if (id==null&&name!=null) {
			
			coach.setCname(name);
			
			venue.setVname(name);
			
			user.setUname(name);
		}else if (id!=null&&name!=null) {
			
			
			coach.setCname(name);
			coach.setCid(id);
			
			venue.setVname(name);
			venue.setVid(id);
			
			user.setUname(name);
			user.setUid(id);
		}*/

		List<Object> findlist=new ArrayList<>();
		//遍历查找出的教练
		List<Coach> coachs=coachService.findCoachByName(name);
		Iterator<Coach> findcoach=coachs.iterator();
		while (findcoach.hasNext()) {
			Coach coach = (Coach) findcoach.next();
			findlist.add(coach);
		}
		//遍历查找出的学员
		List<User> users=coachService.findUserByName(name);
		Iterator<User> finduser=users.iterator();
		while (finduser.hasNext()) {
			User user = (User) finduser.next();
			findlist.add(user);
		}
		//遍历查找出的场馆
		List<Venue> venues=coachService.findVenueByName(name);
		Iterator<Venue> findvenue=venues.iterator();
		while (findvenue.hasNext()) {
			Venue venue = (Venue) findvenue.next();
			findlist.add(venue);
		}
		
		ResponseEntity<List<Object>> entity=new ResponseEntity<>();
		if (findlist.size()>0) {
			
			entity.setData(findlist);
			return entity;
		}
			return ResponseEntity.ERROR.setMsg("未找到结果！");
		
		
	}

	// 添加关注
	@RequestMapping("addrelationship")
	@ResponseBody
	public ResponseEntity<Void> addRelationship(Relationship relationship, HttpServletRequest request) {
		// 获取当前用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		//添加关注进数据库
		relationship.setFan(coach.getCid()); 
		//relationship.setFan(100001);
		relationship.setFollowed(relationship.getFollowed());
		relationship.setAvatar(relationship.getAvatar());
		relationship.setNickname(relationship.getNickname());
		coachService.addRelationship(relationship);
		return ResponseEntity.SUCCESS.setMsg("添加成功！");
	}

	// 签约场馆

	@RequestMapping("/myvenue")

	@ResponseBody
	public ResponseEntity<PageBean<Signing>> myVenue(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		ResponseEntity<PageBean<Signing>> entity = new ResponseEntity<PageBean<Signing>>();

		// 通过账号获取cid
		// int cid = 100001;
		// PageBean<Signing> signing = coachService.getVenueByPage(page, cid);
		PageBean<Signing> signing = coachService.getVenueByPage(page, coach.getCid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(signing);
		return entity;
	}

	// 学员列表

	@RequestMapping("/myuser")
	@ResponseBody
	public ResponseEntity<PageBean<Order>> myUser(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		ResponseEntity<PageBean<Order>> entity = new ResponseEntity<PageBean<Order>>();
		// 通过账号获取cid
		// int cid = 100001;
		// PageBean<Order> order = coachService.getUserByPage(page, cid);
		PageBean<Order> order = coachService.getUserByPage(page, coach.getCid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(order);
		return entity;

	}

	// 教练发消息
	@RequestMapping("/coachmessage")
	@ResponseBody
	public ResponseEntity<Void> coachSendMessage(int id, String messages, HttpServletRequest request) {
		// session中获取当前用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// 消息
		 //int cid = 100004;
		Message message = new Message();
		 //message.setSender(cid);
		message.setSender(coach.getCid());
		message.setTarget(id);
		String date = TimeUtils.getNowTime();
		message.setSendTime(date);
		message.setContent(messages);
		message.setPurpose("1");
		message.setMstatus("1");
		int num = messageService.sendMessage(message);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("信息发送成功！");
		}
		return ResponseEntity.ERROR.setMsg("发送失败！");
	}

	// 教练收消息
	@RequestMapping("/acceptmessage")
	@ResponseBody
	public ResponseEntity<PageBean<Message>> coachAcceptMessage(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		ResponseEntity<PageBean<Message>> entity = new ResponseEntity<PageBean<Message>>();
		// 通过账号获取cid
		 //int target = 1;
		 //PageBean<Message> message = messageService.getMessageByPage(page, target);
		PageBean<Message> message = messageService.getMessageByPage(page, coach.getCid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(message);
		return entity;

	}

	// 消息查看后，标记为已读
	@RequestMapping("/wasread")
	@ResponseBody
	public ResponseEntity<Void> messageWasRead(int mid) {
		int num = messageService.changeMessageStatus(mid);
		if (num == 1) {
			return ResponseEntity.SUCCESS;
		}
		return ResponseEntity.ERROR;
	}

	// 对签约邀请回应
	@RequestMapping("/reply")
	@ResponseBody

	public ResponseEntity<Void> replySign(int reply, int vid, HttpServletRequest request) {

		// 从session中获取用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// 接受邀请
		if (reply == 2) {
			// 将该签约信息写入签约表
			Signing signing = new Signing();
			signing.setVid(vid);
			// int cid = 100001;
			// signing.setCid(cid);
			signing.setCid(coach.getCid());
			signing.setSignTime(TimeUtils.getNowTime());
			// 加入签约表
			int num = venueService.insertCoach(signing);
			// 更改邀约信息状态
			coachService.changeRmStatus(vid, coach.getCid(), reply);
			// coachService.changeRmStatus(vid, cid, reply);
			// 发送接受邀约消息
			Message message = new Message();
			message.setSender(coach.getCid());
			// message.setSender(cid);
			message.setTarget(vid);
			message.setSendTime(TimeUtils.getNowTime());
			message.setContent(coach.getNickname() + "接受您的邀约！");
			// message.setContent("教练1接受您的邀约！");
			message.setPurpose("2");
			message.setMstatus("1");
			messageService.sendMessage(message);
			if (num == 1) {
				return ResponseEntity.SUCCESS.setMsg("已接受签约！");
			}
		} else if (reply == 3) {
			// 拒绝签约请求
			coachService.changeRmStatus(vid, coach.getCid(), reply);
			// int cid = 100001;
			// coachService.changeRmStatus(vid, cid, reply);
			// 发送拒绝邀约消息
			Message message = new Message();

			message.setSender(coach.getCid());
			// message.setSender(cid);
			message.setTarget(vid);
			message.setSendTime(TimeUtils.getNowTime());
			 message.setContent(coach.getNickname() + "拒绝您的邀约！");
			//message.setContent("教练1拒绝您的邀约！");
			message.setPurpose("2");
			message.setMstatus("1");
			messageService.sendMessage(message);
		}
		return ResponseEntity.ERROR.setMsg("拒绝邀请！");
	}

	// 判断该账号是否为教练好友
	@RequestMapping("/judgerelationship")
	@ResponseBody
	public ResponseEntity<Void> judgeRelationship(int id, HttpServletRequest request) {
		// 从session中获取用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// 判断该账户是否是教练的关注
		// int cid = 100001;
		// int judgecoach = coachService.judgeRelationship(cid, id);
		int judgecoach = coachService.judgeRelationship(coach.getCid(), id);
		// 是教练的关注，判断该账户是否关注价廉
		if (judgecoach == 1) {
			// 判断该账户是否关注教练
			int judgeid = coachService.judgeRelationship(id,coach.getCid());
			// int judgeid = coachService.judgeRelationship(id, cid);
			// 该账户与教练互关，是好友！
			if (judgeid == 1) {
				return ResponseEntity.SUCCESS.setMsg("该账户和教练是好友");
			}

		} else {
			return ResponseEntity.ERROR.setMsg("该账户不是教练的关注！");
		}

		return ResponseEntity.ERROR.setMsg("该账户和教练不是好友");
	}

	// 教练好友列表
	@RequestMapping("/coachfriend")
	@ResponseBody
	public ResponseEntity<List<Integer>> selectCoachFriend(HttpServletRequest request) {

		// 获取当前用户的id
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// User user=(User)session.getAttribute("user");
		// 通过账号获取cid
		// int cid = 100001;
		// 获取好友id的list
		// List<Integer> findlist=coachService.friendRelationship(cid);
		List<Integer> findlist = coachService.friendRelationship(coach.getCid());
		ResponseEntity<List<Integer>> entity = new ResponseEntity<>();
		entity.setCode(200);
		entity.setMsg("ok");
		entity.setData(findlist);
		return entity;
	}

	/*
	 * 学员查看
	 */
	@RequestMapping("/viewUser")
	@ResponseBody
	public ResponseEntity<List<User>> viewUser(HttpSession session) {
		ResponseEntity<List<User>> entity = new ResponseEntity<List<User>>();
		List<User> users = userService.selectAllUser();
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(users);
		return entity;
	}

	/**
	 * 
	 * @param uid
	 * @return 学员详情
	 */
	@RequestMapping("/findUserByUid")
	@ResponseBody
	public ResponseEntity<User> findUserByUid(int uid) {
		User user = userService.findUserByUid(uid);
		ResponseEntity entity = new ResponseEntity<User>(user);
		return entity;
	}

	/*
	 * 给学员留言
	 */
	@RequestMapping("/addMessageUser")
	@ResponseBody
	public ResponseEntity<Void> addMessageUser(int id, String messages, HttpServletRequest request) {
		if (messages == null || messages.trim().equals("")) {
			return ResponseEntity.ERROR.setMsg("信息不能为空！");
		}
		// session中获取当前用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		// 消息

		// int cid=100001;
		Message message = new Message();
		// message.setSender(cid);
		message.setSender(coach.getCid());
		
		message.setTarget(id);
		String date = TimeUtils.getNowTime();
		message.setSendTime(date);
		message.setContent(messages);
		message.setPurpose("1");
		message.setMstatus("1");
		int num = messageService.sendMessage(message);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("信息发送成功！");
		}
		return ResponseEntity.ERROR.setMsg("发送失败！");
	}

	/**
	 * 添加我的学员
	 */
	@PostMapping("/addMyStudent")
	@ResponseBody
	public ResponseEntity<Void> addMyStudent(int uid, HttpSession session) {
		MyStudent myStudent = new MyStudent();
		int cid = (int) session.getAttribute("cid");
		myStudent.setCid(cid).setUid(uid);
		int code = coachService.addMyStudent(myStudent);
		if (code == 1) {
			// 添加成功
			return ResponseEntity.SUCCESS;
		} else if (code == 2) {
			return ResponseEntity.ERROR.setCode(code).setMsg("已经是你的学员，不能再添加");
		} else {
			return ResponseEntity.ERROR.setCode(code);
		}
	}

	/*
	 * 学员交易次数查看
	 */
	@RequestMapping("/findOrderCountByUid")
	@ResponseBody
	public ResponseEntity<Integer> findOrderCountByUid(int uid) {
		int data = orderService.findOrderCountByUid(uid);
		ResponseEntity entity = new ResponseEntity();
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(data);
		return entity;
	}

	/*
	 * 学员好评次数查看
	 */
	@RequestMapping("/findNiceOrderCountByUid")
	@ResponseBody
	public ResponseEntity<Integer> findNiceOrderCountByUid(int uid) {
		int data = orderService.findNiceOrderCountByUid(uid);
		ResponseEntity entity = new ResponseEntity();
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(data);
		return entity;
	}

	/*
	 * 学员中评次数查看
	 */
	@RequestMapping("/findComOrderCountByUid")
	@ResponseBody
	public ResponseEntity<Integer> findComOrderCountByUid(int uid) {
		int data = orderService.findComOrderCountByUid(uid);
		ResponseEntity entity = new ResponseEntity();
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(data);
		return entity;
	}

	/*
	 * 学员差评次数查看
	 */
	@RequestMapping("/findBadOrderCountByUid")
	@ResponseBody
	public ResponseEntity<Integer> findBadOrderCountByUid(int uid) {
		int data = orderService.findBadOrderCountByUid(uid);
		ResponseEntity entity = new ResponseEntity();
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(data);
		return entity;
	}

	/**
	 * 我的好友动态查看
	 */
	@RequestMapping("/findMyFriendsDynamic")
	@ResponseBody
	public ResponseEntity<List<Dynamic>> findMyFriendsDynamic(HttpSession session) {
		// 查询所有好友
		int cid = (int) session.getAttribute("cid");
		List<Integer> list = coachService.friendRelationship(cid);
		// 假设查出好友
		// List<Integer> list = new ArrayList<>();
		// list.add(10000000);
		// list.add(10000001);
		// 遍历查询好友动态
		List<Dynamic> dy = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			int sender = list.get(i);
			List<Dynamic> temp = dynamicService.findDynamicBySender(sender);
			dy.addAll(temp);
		}
		ResponseEntity<List<Dynamic>> entity = new ResponseEntity<List<Dynamic>>(dy);
		return entity;
	}

	/**
	 * 添加空闲时间
	 */
	@RequestMapping("/addFreetimeByCid")
	public ResponseEntity<Void> addFreetimeByCid(String day, String when, HttpSession session) {
		int cid =(int)session.getAttribute("cid");
		// 判断是否已经添加
		int error = coachService.isFreetimeByCid(cid, day, when);
		if (error == 1) {
			// 已存在
			return ResponseEntity.ERROR.setMsg("请勿重复添加");
		}
		// 添加数据
		int code = coachService.addFreetimeByCid(cid, day, when);
		if (code == 1) {
			// 添加成功
			return ResponseEntity.SUCCESS;
		} else {
			return ResponseEntity.ERROR.setCode(code);
		}


	}

	// 教练发起签约场馆
	@RequestMapping("/coachsign")
	@ResponseBody
	public ResponseEntity signMessage(int id, HttpServletRequest request) {
		// session中获取当前用户
		HttpSession session = request.getSession();
		Coach coach = (Coach) session.getAttribute("coach");
		int cid = coach.getCid();
		// 消息
		int code = signingService.isSigning(cid, id);
		if(code!=1) {
			return ResponseEntity.ERROR.setMsg("你已经是该场馆教练！");
		}
		Message message = new Message();

		// int cid = 100001;
		// message.setSender(cid);
		message.setSender(coach.getCid());

		
		// message.setSender(venue.getVid());

		message.setTarget(id);
		String date = TimeUtils.getNowTime();
		message.setSendTime(date);
		message.setContent(coach.getNickname() + "想加入大家庭！");
		// message.setContent("我是第一教练我想加入你们！");
		// 1表示普通消息2表示签约信息
		message.setPurpose("2");
		// 1表示为确认2表示接受3表示拒绝
		message.setMstatus("1");
		int num = messageService.sendMessage(message);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("签约信息已发送！");
		}
		return ResponseEntity.ERROR.setMsg("签约信息发送失败！");
	}
}